package com.gaohc.wx.wx;

import cn.hutool.crypto.SecureUtil;
import com.gaohc.common.config.WxMaProperties;
import com.gaohc.wx.wx.dto.WxCheckInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping("/wx/")
@RequiredArgsConstructor
public class WxController {

    private final WxMaProperties wxMaProperties;

    @GetMapping("/checkSignature")
    public String checkSignature(WxCheckInfo info) {
        try {
            String timestamp = null != info.getTimestamp() ? info.getTimestamp() : "";    //时间戳
            String nonce = null != info.getNonce()  ? info.getNonce()  : "";                //随机字符串
            String signature = null != info.getSignature() ? info.getSignature()  : "";    //签名
            String echostr = null != info.getEchostr()  ? info.getEchostr()  : "";          //自定义字符串，验证成功后原样返回

            String token = wxMaProperties.getConfigs().get(0).getToken();       //明文
            String[] tokenArray = new String[]{timestamp, nonce, token};
            Arrays.sort(tokenArray);        //排序
            //排序后的字符串
            StringBuilder sb = new StringBuilder();
            for (String s : tokenArray) {
                sb.append(s);
            }
            String local_signature = SecureUtil.sha1(String.valueOf(sb)); //sha1加密
            if (local_signature.equals(signature)) {
                return echostr;    //验证成功，返回echostr给微信服务器
            } else {
                return String.valueOf(false);
            }
        } catch (Exception e) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(bs));
            return String.valueOf(false);
        }
    }
}
